package rootdb

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/xgodb"
	"gitee.com/xiaoyutab/xgotool/xnum"
)

// 获取文件列表信息
// 该函数调用了设备列表，用于确定某日志文件在某设备中是否存在
//
//	min	最小ID，0-查询所有
//	max	最大ID，0-查询所有
func FileListAll(min, max int64) ([]File, error) {
	if min > 0 && min <= xgodb.GetInt("RUN_LOG_MIN_ID") {
		min = xgodb.GetInt("RUN_LOG_MIN_ID")
	}
	if min <= 0 {
		min = time.Now().UnixNano()
	}
	if max <= 0 {
		max = time.Now().UnixNano()
	}
	f := File{}
	mod := []File{}
	// 获取日志文件信息
	conn, err := Connect()
	if err != nil {
		return nil, err
	}
	db := conn.Table(f.TableName()).
		Order("id DESC").
		Where("min_id = 0 or max_id = 0 or "+
			"( min_id <= ? and max_id >= ? ) or "+
			"( min_id <= ? and max_id >= ? ) or "+
			"( min_id > ? and max_id < ? )",
			min, min,
			max, max,
			min, max,
		).
		Where("is_deleted", 0)
	err = db.Find(&mod).Error
	if err != nil {
		return nil, err
	}
	// 获取设备信息
	dervice_list, err := DerviceList()
	if err != nil {
		return nil, err
	}
	for i := 0; i < len(mod); i++ {
		for j := 0; j < len(dervice_list); j++ {
			if xnum.InArray(mod[i].Name, dervice_list[j].NamesList) {
				mod[i].DerviceIds = append(mod[i].DerviceIds, dervice_list[j])
			}
		}
	}
	return mod, nil
}
